package com.hmtech.aup.network

import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.google.gson.Gson
import com.hmtech.aup.App
import com.hmtech.aup.data.auth.CategoryApiService
import com.hmtech.aup.data.auth.UserApiService
import com.hmtech.aup.domain.vo.BaseResponse
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClient {
    private const val BASE_URL = "https://113zhwh63888.vicp.fun/"

    val gson = Gson()

    private val okHttpClient = OkHttpClient.Builder()
        .addInterceptor { chain ->
            val request = chain.request()
            val response = chain.proceed(request)

            val responseBody = response.peekBody(Long.MAX_VALUE)
            val bodyString = responseBody.string()

            try {
                // 使用 Gson 解析响应为 BaseResponse<Any>
                val baseResponse = gson.fromJson(bodyString, BaseResponse::class.java)

                if (baseResponse.code != 200) {
                    android.os.Handler(Looper.getMainLooper()).post {
                        Toast.makeText(
                            App.instance,
                            baseResponse.msg,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }

            } catch (e: Exception) {
                Log.e("HTTP", "Interceptor parse error: ${e.message}")
            }
            response
        }.build()

    private val retrofit = Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val userApiService: UserApiService = retrofit.create(UserApiService::class.java)
    val categoryApiService: CategoryApiService = retrofit.create(CategoryApiService::class.java)


    //        .addInterceptor { chain ->
//            val originalRequest = chain.request()
//
//            // 从本地获取 token（这里以 SharedPreferences 为例）
//            val token = TokenUtils.getTokenFromLocal(null)
//
//            // 如果有 token，添加到请求头
//            val requestWithToken = if (!token.isNullOrEmpty()) {
//                originalRequest.newBuilder()
//                    .header("Authorization", "Bearer $token") // 或其他你的 token 格式
//                    .build()
//            } else {
//                originalRequest
//            }
//            chain.proceed(requestWithToken)
//        }
}